package com.app.oral.service

import com.app.oral.dao.FileDeleteFailureMapper
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

/**
 * 文件删除重试服务
 */
@Service
class FileDeleteRetryService(
    private val weChatCloudFileDeleteService: WeChatCloudFileDeleteService,
    private val fileDeleteFailureMapper: FileDeleteFailureMapper
) {
    
    private val logger = LoggerFactory.getLogger(FileDeleteRetryService::class.java)
    
    /**
     * 每小时执行一次：重试删除失败的文件
     */
    @Scheduled(fixedRate = 3600000) // 1小时 = 3600000毫秒
    fun retryFailedFileDeletes() {
        logger.info("开始执行定时文件删除重试任务")
        
        try {
            val successCount = weChatCloudFileDeleteService.retryDeleteFailedFiles()
            logger.info("定时文件删除重试任务完成，成功删除{}个文件", successCount)
        } catch (e: Exception) {
            logger.error("定时文件删除重试任务执行失败", e)
        }
    }
    
    /**
     * 每天凌晨2点执行：清理超过30天的永久失败记录
     */
    @Scheduled(cron = "0 0 2 * * ?")
    fun cleanupOldFailedRecords() {
        logger.info("开始清理超过30天的永久失败记录")
        
        try {
            val deletedCount = fileDeleteFailureMapper.deleteOldFailedRecords(30)
            logger.info("清理完成，删除了{}条超过30天的永久失败记录", deletedCount)
        } catch (e: Exception) {
            logger.error("清理永久失败记录时发生异常", e)
        }
    }
    
    /**
     * 获取文件删除失败统计信息
     */
    fun getFailureStatistics(): Map<String, Int> {
        return try {
            mapOf(
                "pending" to fileDeleteFailureMapper.countByStatus(com.app.oral.model.FileDeleteStatus.PENDING),
                "retrying" to fileDeleteFailureMapper.countByStatus(com.app.oral.model.FileDeleteStatus.RETRYING),
                "failed" to fileDeleteFailureMapper.countByStatus(com.app.oral.model.FileDeleteStatus.FAILED),
                "deleted" to fileDeleteFailureMapper.countByStatus(com.app.oral.model.FileDeleteStatus.DELETED)
            )
        } catch (e: Exception) {
            logger.error("获取文件删除失败统计信息时发生异常", e)
            emptyMap()
        }
    }
}